class UsersController < ApplicationController
  before_filter :set_nav_session
  before_filter :login_required, :except => [:new, :create, :show, :confirmed_schools, 
                                            :unconfirmed_schools, :neighbors, :published_events, :activate]
  
  # render new.rhtml
  def new
  end

  def create
    @user = User.new(params[:user])
    @user.ref = "dizhen.1kg.org"
    @user.save!
    self.current_user = @user
    redirect_back_or_default('/')
  rescue ActiveRecord::RecordInvalid
    render :action => 'new'
  end
  
  def activate
    self.current_user = User.find_by_activation_code(params[:activation_code])
    if logged_in? && !current_user.activated?
      current_user.activate
      flash[:notice] = "帐户已经激活"
    end
    redirect_back_or_default('/')
  end
  
  # for personel's setting
  def edit
    @user = current_user
  end
  
  def update
    @user = User.find(params[:id])
    
    # convert user's avatar to gif format, thanks for Robin Lu
    iconfile = params[:user][:avatar_url]
    unless iconfile.blank?
      # if user upload avatar, convert file format
      img = ::Magick::Image::from_blob(iconfile.read).first
      img.crop_resized!(72,72)
      filename = File.join(RAILS_ROOT + "/public/user/avatar_url/tmp", 'icon.gif')
      img.write(filename)
      iconfile = File.open(filename)
      params[:user][:avatar_url] = iconfile
    end
    params[:user][:blog_url] = correct_url(params[:user][:blog_url])
    
    @user.update_attributes!(params[:user])
    flash[:notice] = "你刚刚修改了个人资料"
    respond_to do |format|
      format.html { redirect_to home_path }
    end
  end
  
  def changepassword
    @user = current_user
  end
  
  def updatepassword
    @user = User.authenticate(current_user.email, params[:user][:old_password])
    if @user.blank?
      redirect_to '/setting/changepassword' 
    else
      @user.update_attributes!(params[:user])
      self.current_user = @user
      flash[:notice] = "成功修改密码"
      redirect_back_or_default('/')
    end
  rescue ActiveRecord::RecordInvalid
    render :action => 'changepassword'
  end
  
  def show
    @user = User.find(params[:id])
    @neighbors = @user.neighbors.find(:all, :limit => 12)
    @who_add_me = Relationship.find_by_sql("select count(*) as count from relationships where neighbor_id = #{@user.id}")
    @schools = @user.submitted_schools.find(:all, :conditions => {:is_hidden => false}, :select => "id, is_validate")
    @photos = @user.photos
    @events = @user.events
    @visiteds = Visited.find(:all, :conditions => {:user_id => @user.id}, 
                                          :order => "visiteds.created_at desc",
                                          :include => [:school])
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "没有找到您查看的用户"
    redirect_to home_url    
  end
  
  def published_events
    @user = User.find(params[:id])
    @events = @user.submitted_events
  end
  
  def neighbors
    @user = User.find(params[:id])
    @neighbors = @user.neighbors
  end
  
  # only myself can see who add me
  def who_add_me
    @user = User.find(params[:id])
    redirect_back_or_default(user_path(@user.id)) unless current_user.id == @user.id
    @who_add_me = Relationship.find(:all, :conditions => {:neighbor_id => @user.id}, :order => "relationships.created_at desc", :include => :user)
  end
  
  def confirmed_schools
    @user = User.find(params[:id])
    @schools = School.submitted_by(@user)
  end
  
  def unconfirmed_schools
    @user = User.find(params[:id])
    @schools = School.submitted_by(@user, false)
  end
  
  # add to neighbors of current_user
  def add
    @user = User.find(params[:id])
    relationship = Relationship.find(:first, :conditions => {:user_id => current_user.id, :neighbor_id => @user.id})
    if relationship
      flash[:notice] = "#{@user.login}已经是您的友邻了"
      redirect_back_or_default(user_path(@user.id))
    else
      relationship = Relationship.new
      relationship.user = current_user
      relationship.neighbor = @user
      relationship.save!
      flash[:notice] = "加#{@user.login}为友邻"
      redirect_back_or_default(user_path(@user.id))
    end
  end
  
  # remove from neighbors of current_user
  def remove
    @user = User.find(params[:id])
    relationship = Relationship.find(:first, :conditions => {:user_id => current_user.id, :neighbor_id => @user.id})
    if relationship
      relationship.destroy
      flash[:notice] = "#{@user.login}已经不是您的友邻了"
    end
    redirect_back_or_default(user_path(@user))
  end
  
  private
  def correct_url(url)
    unless url.to_s.empty?
      unless url =~ /^http\:\/\//
        "http://#{url}"
      else
        url
      end
    end
  end

  def set_nav_session
    session[:nav] = "user"
  end
end
